import './style.css'
import { Tabs } from 'antd-mobile'
import { useTabs } from './useTabs.ts'
import HomeList from './HomeList'
import { useState } from 'react'

// 动态控制激活的Tab页:
// 1.使用 localStorage 存储当前激活的频道ID
// 2.使用 activeKey 状态控制当前激活的Tab
// 3.通过 onChange 事件处理Tab切换并保存状态

const Home = () => {
  const { channels } = useTabs()
  // 获取上次保存的频道ID，如果没有则默认为空字符串
  const savedChannelId = localStorage.getItem('active-channel-id') || ''
  const [activeKey, setActiveKey] = useState(savedChannelId)

  // Tab切换时的处理函数
  const onTabChange = (key: string) => {
    console.log('切换到', key)
    // 保存当前激活的频道ID
    localStorage.setItem('active-channel-id', key)
    setActiveKey(key)
  }

  return (
    <div>
      <div className="tabContainer">
        <Tabs activeKey={activeKey} onChange={onTabChange}>
          {channels.map((item) => (
            <Tabs.Tab title={item.name} key={item.id}>
              <div className="listContainer">
                <HomeList channelId={'' + item.id} />
              </div>
            </Tabs.Tab>
          ))}
        </Tabs>
      </div>
    </div>
  )
}

export default Home
